package com.csw.android.ffmpegtest.camera

import android.content.Context
import android.graphics.ImageFormat
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.hardware.camera2.params.StreamConfigurationMap
import com.csw.android.ffmpegtest.app.MyApplication

/**
 * CameraCharacteristics.LENS_FACING :
 * 获取摄像头方向。前置摄像头（LENS_FACING_FRONT）或 后置摄像头（LENS_FACING_BACK）
 * CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL：
 * 获取当前设备支持的相机特性
 * CameraCharacteristics.SENSOR_ORIENTATION：
 * 获取摄像头方向
 * CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP：
 * 获取StreamConfigurationMap，它是管理摄像头支持的所有输出格式和尺寸
 * CameraCharacteristics.FLASH_INFO_AVAILABLE：
 * 是否支持闪光灯
 * CameraCharacteristics.STATISTICS_INFO_MAX_FACE_COUNT:
 * 同时检测到人脸的数量
 * CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES:
 * 相机支持的人脸检测模式
 */
class CameraSelector {
    /**
     * 摄像头面向
     */
    var facing: Int = CameraCharacteristics.LENS_FACING_FRONT

    /**
     * 摄像头支持输出的图像格式
     */
    var imageFormat: Int = ImageFormat.YUV_420_888

    /**
     * 摄像头支持输出的图像格式
     */
    var selectedCameraOrientation: Int = 0

    /**
     * 根据条件选择一个摄像头
     */
    fun selectCamera(): String? {
        val cameraManager =
            MyApplication.instance.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        var characteristics: CameraCharacteristics
        var cameraFacing: Int? = null
        var config: StreamConfigurationMap? = null
        var orientation: Int? = null
        for (id in cameraManager.cameraIdList) {
            characteristics = cameraManager.getCameraCharacteristics(id)
            cameraFacing = characteristics.get(CameraCharacteristics.LENS_FACING)
            config = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
            orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)
            if (cameraFacing == facing) {
                config?.run {
                    if (isOutputSupportedFor(imageFormat)) {
                        selectedCameraOrientation = orientation ?: 0
                        return id
                    }
                }
            }
        }
        return null
    }

}